package com.sishu.websocket4.config;

import com.sishu.websocket4.common.WebSocketAPI;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.annotation.Resource;

/**
 * @Date: 2020/10/16 13:55
 */
//配置类
@Configuration
//启动websocket
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private WebSocketAPI webSocketAPI;


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
         //当浏览器，websocket的请求路径是/websocketMessage的时候，就会调用到webSocketAPI中的方法
        registry.addHandler(webSocketAPI,"/websocketMessage")
                .setAllowedOrigins("*")
                // 通过注册特定的HttpSession拦截器，就可以把
                // 用户给HttpSession中添加的Attribute键值对，往WebSocketSession中也添加一份
                .addInterceptors(new HttpSessionHandshakeInterceptor());
    }

}
